/*
 * Copyright 2009-2010 Belmont Software Services
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.belmont.backup;

import java.io.*;
import com.marimba.intf.util.IConfig;
import com.marimba.intf.application.*;
import com.belmont.backup.gui.*;
import com.belmont.backup.*;

/*

  Channel entry-point to backup client

  On startup the channel checks the following properties:

  - belmont.backup.config.checked=<tm>
  - belmont.backup.config.check.interval=N

  If the first property is null or the timestamp is older then N hours
  from the current time then the config is retrieved from the server
  and the checked property is updated.

  - belmont.backup.schedule=<schedule> which contains a string
    readable by Utils.nextScheduleTime and indicates the schedule for
    automatic backups.
    

 */
public class BackupChannelMain implements IApplication, IBackupConstants {
    IApplicationContext context;
    IConfig config;
    IConfig tunerConfig;
    File dataDir;
    BackupApplication app;
    GuiMain gui;

    public void notify(final Object sender, final int msg, final Object arg) {
	switch (msg) {
	case APP_INIT:
	    context = (IApplicationContext) arg;
	    config = context.getConfiguration();
	    dataDir = new File(context.getDataDirectory());
	    break;
	case APP_START:
	    try {
		tunerConfig = (IConfig)context.getFeature("config");
		/*
		String pairs[] = tunerConfig.getPropertyPairs();
		System.out.println("PROPERTIES");
		for (int i=0; i < pairs.length; i += 2) {
		    System.out.println("PROP "+pairs[i]+"="+pairs[i+1]);
		}
		*/
		Utils.installChannelDLLs(tunerConfig, context);
		app = new BackupApplication(context);
		app.init();
	    } catch (IOException ex) {
		ex.printStackTrace();
		context.stop();
	    }
	    break;
	case APP_ARGV:
	    {
		String argv[] = (String[])arg;
		
		if (argv.length > 0 && "-GUI".equals(argv[0])) {
		    if (gui == null) {
			try {
			    gui = new GuiMain(app);
			    gui.init();
			    gui.start();
			    gui.show();
			} catch (IOException ex) {
			    ex.printStackTrace();
			    app.stop();
			}
		    } else {
			gui.show();
		    }
		} else if (gui == null) {
		    long tm = app.nextScheduledBackup();
		    long now = System.currentTimeMillis();
		    if (app.getConnected()) {
			if ((tm - now) > 60000) {
			    app.stop();
			} else if (tm == 0) {
			    String cfi = config.getProperty(CONFIG_CHECK_CONFIG_INTERVAL);
			    int checkInterval = DEFAULT_CHECK_CONFIG_INTERVAL;
			    if (cfi != null) {
				try {
				    checkInterval = Integer.parseInt(cfi);
				} catch (NumberFormatException ex) {
				    ex.printStackTrace();
				}
			    }
			    System.out.println("No scheduled backup. Restarting in "+checkInterval+" minutes.");
			    context.startLater(now + (checkInterval * 60000), null);
			    context.stop();
			}
		    } else {
			// error connecting check again later
			// XXX: make this configurable
			System.out.println("App not connected. Starting again in 5 minutes.");
			context.startLater(now + (5 * 60000), null);
			context.stop();
		    }
		}
	    }
	    break;
	case APP_DATA_AVAILABLE:
	    break;
	case APP_DATA_NONE_AVAILABLE:
	    break;
	case APP_DATA_INSTALLED:
	    break;
	case APP_STOP:
	    stop();
	    break;
	}
    }

    public void stop() {
	app.stop();
    }

}